package com.yyge.web.servlet;

import cn.hutool.crypto.digest.BCrypt;
import com.yyge.dao.Impl.UserInfoDaoImpl;
import com.yyge.entity.BaseEntity;
import com.yyge.entity.Userinfo;
import com.yyge.util.JwtUtile;
import com.yyge.util.ServletUtil;
import com.yyge.vo.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户登录的API
 * 方法：POST
 * 参数：账号+密码
 */

@WebServlet("/logon/")
public class UserinfoLogon extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BaseEntity baseEntity = ServletUtil.fetchDataFromRequest(req,Userinfo.class);
        Map<String, Object> params = baseEntity.getParams();
        Userinfo targrt = (Userinfo) baseEntity;
        String userName=targrt.getName();
        String userPassWord=targrt.getPassword();

        UserInfoDaoImpl impl=new UserInfoDaoImpl();

        /*根据名称查找对象*/
        Userinfo user = impl.Logon(targrt);

        /**
         * 密码验证利用hutool
         */
        //md5增强版 bcrypt --> Hutool工具类实现的 密码
        boolean correct= BCrypt.checkpw(userPassWord, user.getPassword());

        R r=new R();
        if(!correct){
            r=R.fail("账号密码错误!登录失败");
        }else{
            //登陆成功要设置为当前用户设置Token
            String token = JwtUtile.getToken(user.getName(), user.getPassword());
            user.setToken(token);
            impl.modify(user);
            r=R.ok(user);
        }

        ServletUtil.writeResult2Client(resp,r);
    }
}
